﻿using System;
using System.IO;

namespace DAPNet
{
    public abstract class SampleConverter
    {
        public abstract Sample ReadSample(BinaryReader waveReader);

        public abstract void WriteSample(BinaryWriter waveWriter, Sample sample);

        protected static Sample ValueToSample(double value, double minValue, double maxValue)
        {
            double sampleValue = GetCorrespondingValue(value, minValue, maxValue, Sample.MinValue, Sample.MaxValue);
            return new Sample(sampleValue);
        }

        protected static double SampleToValue(Sample sample, double minValue, double maxValue)
        {
            double value = GetCorrespondingValue(sample.Value, Sample.MinValue, Sample.MaxValue, minValue, maxValue);
            return value;
        }

        private static double GetCorrespondingValue(
           double value,
           double sourceMinValue,
           double sourceMaxValue,
           double targetMinValue,
           double targetMaxValue)
        {
            double normalizedValue = value - sourceMinValue;
            double sourceInvervalSize = GetIntervalSize(sourceMinValue, sourceMaxValue);
            double targetIntervalSize = GetIntervalSize(targetMinValue, targetMaxValue);
            double conversionRatio = targetIntervalSize / sourceInvervalSize;
            double convertedNormalizedValue = normalizedValue * conversionRatio;
            double correspondingValue = convertedNormalizedValue + targetMinValue;
            return correspondingValue;
        }

        private static double GetIntervalSize(double minValue, double maxValue)
        {
            return (maxValue - minValue);
        }
    }
}
